<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Tangerine">
    <!--link href='http://fonts.googleapis.com/css?family=Sunshiney' rel='stylesheet' type='text/css' -->
    <!-- link href='http://fonts.googleapis.com/css?family=Annie+Use+Your+Telescope' rel='stylesheet' type='text/css' -->
    <!-- link href='http://fonts.googleapis.com/css?family=Patua+One' rel='stylesheet' type='text/css' -->
    <!--link href='http://fonts.googleapis.com/css?family=Gochi+Hand' rel='stylesheet' type='text/css' -->
    <!--link href='http://fonts.googleapis.com/css?family=Fondamento' rel='stylesheet' type='text/css' -->
    <link href='http://fonts.googleapis.com/css?family=Short+Stack' rel='stylesheet' type='text/css'>

  <style>

body {
    background: url(../images/6255477684_6a54429ac6_m_d.jpg) ;

        -webkit-touch-callout: none;
        -webkit-user-select: none;
        -khtml-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;

}

.stickynote {
        width:  200px;
        height: 200px;
        border-top: 1px solid gray;
        border-left: 1px solid gray;
        border-bottom: 3px solid black;
        border-right: 2px solid gray;
        position: absolute;
        cursor: pointer;

        padding: 10px;
        background: #FFFFAA;
        cursor: default;
        -moz-border-radius: 4px;
        -webkit-border-radius: 4px;
        -khtml-border-radius: 4px;
        border-radius: 4px;
}

.stickynote div.text {
        width:  195px;
        height: 180px;
        font-family: 'Short Stack', sans-serif;
        font-size: 16px;
        cursor: pointer;

        -webkit-touch-callout: none;
        -webkit-user-select: none;
        -khtml-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
}

.stickynote div.edit {
        width:  190px;
        height: 180px;
        display: none;
}

.stickynote div.edit textarea {
            height: 80%;
            width: 98%;

}

button {
        cursor: pointer;
        border: 1px solid gray;
     -moz-border-radius: 3px;
    -webkit-border-radius: 3px;
    -khtml-border-radius: 3px;
    border-radius: 3px;
        font-family: sans-serif;
}

button:hover {
    background: #FFFFFF;
}

.stickynote button.update {
}

.stickynote button.cancel {
}

.stickynote button.delete {
    background: #FFCCCC;
}

.hidden { display: none }


div.toolbar {
    position: absolute;
    top: 0px;
    right: 0px;
}

  </style>
  
  </head>


  <body>
    
  <div class='toolbar'>
   <button class="newnote" id="button-newnote">make a new note</button>
   &nbsp;
   &nbsp;
   <button class="changefolder" id="button-changefolder">switch board</button><input type=text id="input-foldername" size=20 value="" >
  </div>
   <div class='hidden'>
    <div id='stickynote-sample' class='stickynote' 
    >
        <div class='text'
            title='double click to edit note' 
            >
        </div>
        <div class='edit'>
            <textarea >
            </textarea>
            <button class='update'>save</button>
            <P>
            <button class='cancel'>cancel</button>
            <button class='delete'>delete this note</button>
        </div>
    </div>
   </div>
    <div id="draggables"></div>
    


   <div class='hidden'>
    <pre id='debug1'> </pre>
    <pre id='debug2'> </pre>
   </div>






    <script>
    function htmlize(text) {
        text  =  text
                .replace( /'''''([_\w\s]+)'''''/g, "<b><i>$1</i></b>")
                .replace( /'''([_\w\s]+)'''/g, "<b>$1</b>")
                .replace( /''([_\w\s]+)''/g, "<i>$1</i>")
                .replace(/\n\s*----\s*\n/g, "<hr>")
                .replace(/\n\s*\n/g, "<br>");

        return text;
    }

    var clientId;
    var currentFolder;
    var currentItems = {};
    function resetStickyNotes() {
        currentItems = {};
      	$('#draggables').html("");
    }
    var newpos = 1;
    function updateStickyNotes(data)  {
            var foundItems = {};
            $(data).each(function() {
                                if ( ! this.data ) { return;  }
                                var name = this.name;
                                var tag = this.tag;
                                this.data = this.data || { text: null };
                                this.meta = this.meta || { x: 100, y : 100 };
                                foundItems[name] = this;
                                var current = currentItems[name]
                                if ( current && tag == current.tag ) { return;  }
                                var id = "stickynote-" + this.name;
                                var el = $(document).findOrCreate( "#"+id, function(jq) {
                                    var el = $("#stickynote-sample").clone(false);
                    				el.attr('id', id );
                                    el.hide();
                					$('#draggables').append( el ); 
                                    el.draggable(); 
                                    el.find("div.text").bind( "dblclick", function(event, ui) {
                                        el.find("div.text").hide();
                                        el.find("div.edit").show();
                                    } );
                                    el.find("div.edit button.cancel").bind( "click", function(event, ui) {
                                        el.find("div.edit").hide();
                                        el.find("div.text").show();
                                    } );
                                    el.fadeIn();
                                    return el;
                                } );

                                el.draggable( 'option', 'cursor', 'pointer' );
                                el.find("div.text").html( htmlize( this.data.text || "(empty)"  ) );
                                el.find("div.edit textarea").val( this.data.text || "" );
                                //el.find("div.edit").hide();
                                //el.find("div.text").show();
                                el.unbind("dragstop");
                                el.bind( "dragstop", function(event, ui) {
                                    storePosition( name, tag, ui.offset.left, ui.offset.top );
                                }); 
                                el.find("div.edit button.update").unbind( "click");
                                el.find("div.edit button.update").bind( "click", function(event, ui) {
                                        storeText( name, tag, el.find("div.edit textarea").val(),
                                               function() {
                                                el.find("div.edit").hide();
                                                el.find("div.text").show();
                                               } );
                                    } );
                                el.find("div.edit button.delete").unbind( "click");
                                el.find("div.edit button.delete").bind( "click", function(event, ui) {
                                        el.fadeOut();
                                        deleteItem( name, tag );
                                    } );

                                if ( this.meta && this.meta.x && this.meta.y ) {
                                    el.offset( { top: this.meta.y, left: this.meta.x });
                                }
                                if ( this.data.edit && this.data.edit == clientId ) {
                                        el.find("div.text").hide();
                                        el.find("div.edit").show();
                                }
                            }
               );
               for ( var n in currentItems ) {
                       if ( ! foundItems[n] ) {
                            $("#"+"stickynote-"+n).fadeOut();
                            delete currentItems[n];
                       }
               }
               currentItems = foundItems;

    
   }
    







    var xhr = null;
    function setupChannel( observeTag ) {
        if ( xhr ) {
                xhr.abort();
        }
      	xhr = new XMLHttpRequest();
    	xhr.onreadystatechange  =  function()
                                {
                                        if( xhr.readyState == 4 )  {
                                               if ( xhr.status == 200 ) {
                                                    var newtag = parseInt(xhr.responseText);
                                                    setupChannel( newtag );
                                                    if ( newtag != observeTag ) {
        				                                fetchStickyNotes();
                                                    }
                                            } else if (xhr.status != 0 )  {
                                                setTimeout( function() {
                                                            setupChannel( observeTag );
                                                                }, 5000 )
                                            }
                                        }
                                };
                                
    	xhr.open('GET', "../../db/" + currentFolder + "/" + "?observe=1&tag="+observeTag + "&client="+clientId, true);
    	xhr.send();
    }

     function deleteItem( name, tag, callback ) {
      	var xhr = new XMLHttpRequest();
    	xhr.onreadystatechange  =  function()
                                {
                                        if( xhr.readyState == 4 )  {
                                               if ( xhr.status == 200 ) {
                                                       if ( callback ) { callback(); }
                                            } else if (xhr.status != 0 )  {
                                            }
                                        }
                                };
                                
    	xhr.open('DELETE', "../../db/" + currentFolder + "/" + name + "?tag="+tag + "&client="+clientId, true);
    	xhr.send();
    }

    function storeNew( callback ) {
            newpos =  ( ( newpos + 10 + Math.floor(Math.random() * 5  )) % 500 );
            var body = JSON.stringify( {
                        text: "", edit: clientId
            });
            var name = randomString();
        jQuery.post( "../../db/" + currentFolder + "/" + name + "?meta=0&tag=" + 0 + "&client="+clientId, body, function(data) {
                        if (callback) callback();
                        var tag = data[0].tag;
                        storePosition( name, tag, newpos, newpos, function() {
                                } );
        } );
    }



    function storePosition( name, tag, x, y, callback ) {
            var body = JSON.stringify( {
                        x: x,
                        y: y
            });
        jQuery.post( "../../db/" + currentFolder + "/" + name + "?meta=1&tag=" + tag + "&client="+clientId, body, function(data) {
                        if (callback) callback();
        } );
    
    }
    function storeText( name, tag, text, callback ) {
            var body = JSON.stringify( { "text": text } );
        jQuery.post( "../../db/" + currentFolder + "/" + name + "?meta=0&tag=" + tag + "&client="+clientId, body, function(data) {
                        if (callback) callback();

        } );
    
    }
    
    function fetchStickyNotes() { 
        var folder = currentFolder;
        jQuery.getJSON( "../../db/" + folder + "/?client="+clientId , {}, function(data) {
        		$("#debug1").text( JSON.stringify(data, null, 10 ) );
                updateStickyNotes(data);
        		$("#debug2").text( JSON.stringify(currentItems, null, 10 ) );
        } ).error( function() {
                    alert("Couldn't load notes in " + folder );
                }
           );
    }
    
    </script>
    <script type="text/javascript" src="../jquery/jquery-1.7.1.min.js"></script>
    <script type="text/javascript" src="../jquery/jquery-ui-1.8.5.custom.min.js"></script>
    <script type="text/javascript" src="../js/utils.js"></script>
    <script type="text/javascript" >
    	$(function() {

             jQuery.fn.findOrCreate = function(selector, ctor) {
                    var el = this.find(selector);
                    if ( el.length == 0 ) {
                        el = ctor(this);
                    }
                    return el;
             };


            currentFolder =  getHashValueDefault("path", "Test") ;
            clientId = readCookieWithDefault("clientid", randomString() );
            createCookie("clientid", clientId, 1000 );
            clientId = clientId + "." + randomString();

    		$("#button-changefolder").click( function() {
    				currentFolder =  $("#input-foldername").val(); 
                    resetStickyNotes();
    				setupChannel( 1 ); 
    				//fetchStickyNotes();
                    setHashValue("path", currentFolder );
    			} );
    	    $("#input-foldername").val( currentFolder );
            setTimeout(  function() {
        		$("#button-changefolder").click();
                }, 0 );
    		
            $("#button-newnote").click( function() {
                                storeNew();
                            } );
    	} );
    	
    	
    </script>
    
  </body>
</html>
